package com.centerm.bluetooth.common.controller;

import android.content.Context;
import android.support.annotation.NonNull;

import com.centerm.bluetooth.common.Command;
import com.centerm.bluetooth.common.listener.ITerminalSafeListener;
import com.centerm.bluetooth.core.controller.BaseController;
import com.centerm.bluetooth.core.controller.constants.WaitEnum;
import com.centerm.bluetooth.ibridge.BluetoothIBridgeDevice;
import com.centerm.bluetooth.model.Respond;
import com.centerm.util.HexUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by linwenhui on 2017/5/2.
 */

public class TerminalSafeController extends BaseController<ITerminalSafeListener> {

    private final static int TYPE_CAL_MAC = 0x01;
    private int type;

    public TerminalSafeController(@NonNull Context context) {
        super((byte) 0x02,context);
    }

    public boolean calMac(byte[] random, byte[] datas) throws IOException {
        if (wait == WaitEnum.FREE) {
            ByteArrayOutputStream params = new ByteArrayOutputStream();
            params.write(random);
            params.write(0);
            params.write(HexUtil.toHexLen(datas.length));
            params.write(datas);
            type = TYPE_CAL_MAC;
            boolean res = send(Command.CAL_MAC, params.toByteArray());
            if (res)
                setTimeoutTimer();
            params.close();
            return res;
        }
        return false;
    }

    @Override
    public void onDataReceived(BluetoothIBridgeDevice device, Respond respond) {
        super.onDataReceived(device, respond);
        if (type == TYPE_CAL_MAC) {
            parseCalMac(respond.getContent());
        }
    }

    protected void parseCalMac(byte[] macs) {
        if (baseListener != null)
            baseListener.onGetMac(macs);
    }
}
